package org.zebra.logging.task;

import cn.hutool.cron.task.Task;
import cn.hutool.db.Db;
import cn.hutool.extra.spring.SpringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.sql.DataSource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;

/**
 * @author 张红彬
 */
@Slf4j
public class LogScheduleTask implements Task {

    @Override
    public void execute() {
        log.info("LogScheduleTask 任务执行开始: " + LocalDateTime.now());
        DataSource dataSource = SpringUtil.getBean(DataSource.class);
        if (dataSource != null) {
            /**
             * 保留时间
             */
            Long reserveTime = SpringUtil.getApplicationContext()
                    .getEnvironment()
                    .getProperty("zebra.log.reserve-time", Long.class);
            /**
             * 日志表名
             */
            String table =
                    SpringUtil.getApplicationContext().getEnvironment().getProperty("zebra.log.table", String.class);
            // 获取当前时间
            LocalDateTime now = LocalDateTime.now();
            // 减去6个月
            LocalDateTime sixMonthsAgo = now.minus(reserveTime == null ? 6 : reserveTime, ChronoUnit.MONTHS);
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String date = sixMonthsAgo.format(formatter);
            String tableName = StringUtils.isBlank(table) ? "sys_operation_log,sys_audit_log" : table;
            String[] tableNameArray = tableName.split(",");
            for (String name : tableNameArray) {
                try {
                    Db.use(dataSource).execute("delete from " + name + " where create_time <'" + date + "'");
                } catch (Exception e) {
                    log.error("LogScheduleTask 任务执行失败: {}", e.getMessage());
                }
            }
        }
        log.info("LogScheduleTask 任务执行结束: " + LocalDateTime.now());
    }
}
